package com.bruce.service.impl;

import com.bruce.domain.Role;
import com.bruce.domain.User;
import com.bruce.mapper.RoleMapper;
import com.bruce.mapper.UserMapper;
import com.bruce.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<User> list() {
        List<User> userList = userMapper.findAll();
        for (User user: userList) {
            Long id = user.getId();
            List<Role> rolesByUserId = roleMapper.findRoleByUserId(id);
            user.setRoles(rolesByUserId);
        }

        return userList;
    }

    @Override
    @Transactional
    public void save(User user, Long[] roleIds) {
        userMapper.save(user);
        Long userId = user.getId();
        userMapper.saveUserRoleRel(userId, roleIds);
    }

    @Override
    public void del(Long userId) {
        userMapper.delUserRoleRel(userId);
        userMapper.del(userId);
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.findByUsernameAndPassword(username, password);
        return user;
    }
}
